//
//  TFStausListViewModel.swift
//  weiboSina
//
//  Created by admin on 16/1/2.
//  Copyright © 2016年 admin. All rights reserved.
//

import UIKit
import SDWebImage
class TFStausListViewModel: NSObject {

    var statuses:[TFStatusViewModel]?
    /// 加载首页数据
    func loadData(completion: (isSuccessed: Bool)->()){
        
        // 定义请求地址与参数
        let urlString = "https://api.weibo.com/2/statuses/friends_timeline.json"
        
        let params = [
            "access_token": TFUserAccountViewModel.sharedViewModel.accessToken!,
        ]
        
        // 发送请求
        HMNetworkTools.sharedTools.request(urlString: urlString, parameters: params) { (response, error) -> () in
            
            if error != nil {
                print(error)
                //请求失败，回调不成功
                completion(isSuccessed: false)
                return
            }
            
            guard let responseDict = response as? [String: AnyObject] else {
                print("返回数据不是字典")
                completion(isSuccessed: false)
                return
            }
            
            // 字典转模型
            let statusDicts = responseDict["statuses"]! as! [[String: AnyObject]]
            // 定义监听数据，保存转成功的模型
            var tempArray: [TFStatusViewModel] = [TFStatusViewModel]()
            
            // 遍历字典转模型
            for dict in statusDicts {
                let status = TFStatus(dict: dict)
                
                //初始化视图模型
                let statusViewModel = TFStatusViewModel()
                //设置值
                statusViewModel.status = status
                // 把模型添加到数组里面
                tempArray.append(statusViewModel)
            }
            
            // 赋值
            self.statuses = tempArray
            
            //缓存单张图片
            self.cacheSingleImage(tempArray,completion: completion)
            // 刷新数据
        
        }
    }
    
    //缓存单张图片
    private func cacheSingleImage(dataArray: [TFStatusViewModel],completion:(isSuccessed: Bool) -> ()){
    
        var dataLength = 0
    /**
    创建组
    */
    let group = dispatch_group_create()
    
    for viewModel in dataArray {
    
    //判断当前viewModel里面的图片是否是单张
        if viewModel.picUrls?.count != 1 {
        //执行下面的循环
        continue
            
        }
    let urlString = viewModel.picUrls?.first!.thumbnail_pic!
        let url = NSURL(string: urlString!)
        //下载图片
        dispatch_group_enter(group)
        SDWebImageManager.sharedManager().downloadImageWithURL(url, options: [], progress: nil, completed: { (image, error, _, _, _) -> Void in
            
            if image != nil {
            //计算当前下载图片的大小
                dataLength += UIImagePNGRepresentation(image)!.length
            
            }
            //出组
            dispatch_group_leave(group)
            
        })
  }
  dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
    
    //通知刷新界面
    completion(isSuccessed: true)
    
    }
  }
    
}
